package com.ggb.smartstudy.controller;

import com.ggb.smartstudy.entity.Result;
import com.ggb.smartstudy.entity.User;
import com.ggb.smartstudy.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * @author gefangjie
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<User> registerUser(@Valid @RequestBody User user) {
        userService.createUser(user);
        return ResponseEntity.ok(user);
    }

    // 获取当前用户信息
    @GetMapping("/current")
    public Result getCurrentUser() {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 如果当前用户已认证
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
            User u = userService.getUserByUsername(userDetails.getUsername());
            return Result.success(u);
        } else {
            // 未认证
            return Result.error("没有认证啊！小子！");
        }
    }

    // 更新当前用户信息
    @PutMapping("/update")
    public Result updateUserSelf (@Valid @RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 如果当前用户已认证
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
            // 获取当前用户信息
            // 如果当前用户ID与请求ID不一致
            // TODO. 这里是狗屎代码！！！
            if (!userService.getUserByUsername(userDetails.getUsername()).getId().equals(user.getId())) {
                return Result.error("无权修改他人信息");
            } else {
                // 修改传来的用户信息
                userService.updateUser(user);
                // 清除认证信息，自动退出登录状态
                // 使当前会话失效
                new SecurityContextLogoutHandler().logout(request, response, authentication);
                return Result.success("用户信息更新成功，请重新登录！");
            }
        } else {
            // 未认证
            return Result.error("没有认证啊！小子！");
        }
    }
}
